<?php
namespace Home\Controller;

use Think\Controller;
use Home\Common\TPWechat;
use Home\Common\JSSDK;
use Think\Exception;

class IndexController extends Controller
{
    private $wxuser;
    private $open_id;
    private $appid = 'wxb8ff917a0b440163';
    private $appsecret = '2837aa8f9f79f89852b89b7788694357';
    private $token = 'test';
    private $jssdk;
    private $options;
    private $weObj;

    public function _initialize()
    {
        $this->jssdk = new JSSDK($this->appid, $this->appsecret);
        $this->weObj = new TPWechat(array(
            'token' => $this->token, //填写你设定的key
            'appid' => $this->appid, //填写高级调用功能的app id
            'appsecret' => $this->appsecret //填写高级调用功能的密钥
        ));
//        $this->weObj->valid(false);
    }

    private function setSign()
    {
        $signPackage = $this->jssdk->GetSignPackage();
        session('signPackage', $signPackage);
        $this->assign('signPackage', $signPackage);
    }

    public function test1111()
    {
        $this->wxuser = array('open_id' => '1', 'subscribe' => '0');
        session('wxuser', $this->wxuser);
        session('open_id', '1');
        var_dump($this->wxuser);
    }

    public function index()
    {
//        $this->setSign();
        $openid = session('open_id');

        if (!$openid) {
            $this->wxoauth();
        }
        if(!session('open_id')){
            exit;
        }
        $r = M('user')->select();

        foreach ($r as &$item) {
            $item['detail'] = urlencode($item['detail']);
        }
        session('teststr', rand(100000, 999999).',');
        $this->assign('users', $r);

        $this->setSign();
        $this->display('index');
    }

    public function checkSubscribe()
    {
        $user = session('wxuser');
//        var_dump($user);
        return $user && $user['subscribe'] != '0';
    }

    public function checkCode($str) {
        $code = session('teststr');
        if(!$str || !$code || $code == '') {
            return false;
        }
        $index = strpos($str, $code.'');
//        var_dump($code);
//        var_dump($index);
//        var_dump($str);
        if($index !== false) {
            return str_replace($code, '', $str);
        } else {
            return false;
        }
    }

    private function checkip($ip){
//        if(strpos($ip, '61.49.')
//            || strpos($ip, '111.161.')
//            || strpos($ip, '61.158.')
//            || strpos($ip, '218.85.118.')
//            || strpos($ip, '218.85.118.')
//        ){
//            return true;
//        }
        return false;
    }

    // 200: 正确  201:错误  202:未关注  203:系统异常,刷新页面
    public function vote()
    {
        if(time() > 1459094400){
            $data = array('code' => 201, 'msg' => '投票已截止');
            $this->ajaxReturn($data);
            return;
        }
        $votestr = I('param.votestr');
        if(strpos($votestr, ',') < 0){
            $data = array('code' => 201, 'msg' => '禁止僵尸粉~');
            $this->ajaxReturn($data);
            return;
        }
        $votestr = $this->checkCode($votestr);
        if(!$votestr){
            $data = array('code' => 201, 'msg' => '禁止僵尸粉~');
            $this->ajaxReturn($data);
            return;
        }
        $ip = get_client_ip();
        if($this->checkip($ip)){
            $data = array('code' => 201, 'msg' => '禁止僵尸粉~');
            $this->ajaxReturn($data);
            return;
        }
        $this->open_id = session('open_id');
        $access_token = session('user_token');
        $userinfo = $this->weObj->getUserInfo($this->open_id);
        if ($userinfo && !empty($userinfo['nickname'])) {
            $wxuser = array(
                'open_id' => $this->open_id,
                'openid' => $this->open_id,
                'nickname' => $userinfo['nickname'],
                'sex' => intval($userinfo['sex']),
                'province' => $userinfo['province'],
                'city' => $userinfo['city'],
                'headimgurl' => $userinfo['headimgurl'],
                'subscribe' => $userinfo['subscribe']
            );
        }

        if(!$wxuser || $wxuser['subscribe'] == '0'){
            $data = array('code' => 202, 'msg' => '请关注津南团区委后投票');
            $this->ajaxReturn($data);
            return;
        }
        session('wxuser', $wxuser);

        $conditions = array();

        $conditions['open_id'] = $this->open_id;

        try {
            $votestr = I('param.votestr');
            $ids = explode(',', $votestr);
            $ids = array_unique($ids);

            if (!$votestr) {
                $data = array('code' => 201, 'msg' => '投票失败');
                $this->ajaxReturn($data);
                return;
            }
            if (count($ids) > 10) {
                $data = array('code' => 201, 'msg' => '最多只能选10个候选者');
                $this->ajaxReturn($data);
                return;
            }

            if (!$this->checkSubscribe()) {
                $data = array('code' => 202, 'msg' => '请关注津南团区委后投票');
            } else {
                // 已关注,查数据库
                $conditions['open_id'] = $this->open_id;
                $conditions['createtime'] = array('GT', date("Y-m-d 00:00:00"));
                $r = M('vote_log')->where($conditions)->find();
                if ($r) {
                    // 已经投票
                    $data = array('code' => 201, 'msg' => '您今天已经投过票,请明天再来~');
                } else {
                    $user_id = implode(',', $ids);
                    if(strpos($user_id, ',') === false){
                        $data = array('code' => 201, 'msg' => '禁止僵尸粉~');
                        $this->ajaxReturn($data);
                        return;
                    }
                    // 添加投票
                    M('vote_log')->add(array(
                        'open_id' => $this->open_id,
                        'user_id' => implode(',', $ids),
                        'name' => $wxuser['nickname'],
                        'headurl' => $wxuser['headimgurl'],
                        'ip' => get_client_ip()
                    ));
                    foreach ($ids as $key => $value) {
                        M('user')->where('id = %d', $value)->setInc('vote_count');
                    }

                    $data = array('code' => 200, 'msg' => '投票成功');
                }
            }
        } catch (Exception $e) {
            $data = array('code' => 203, 'msg' => '投票的人太多了,请稍后...');
        }
        $this->ajaxReturn($data);
    }

    public function logs(){
        $r = M('vote_log')->select();
        var_dump($r);
    }


    public function wxoauth()
    {
        $scope = 'snsapi_base';
        $code = isset($_GET['code']) ? $_GET['code'] : '';
        $token_time = isset($_SESSION['token_time']) ? $_SESSION['token_time'] : 0;

        $options = array(
            'token' => $this->token, //填写你设定的key
            'appid' => $this->appid, //填写高级调用功能的app id
            'appsecret' => $this->appsecret //填写高级调用功能的密钥
        );
//        $this->weObj = new TPWechat($options);
        if ($code) {
            $json = $this->weObj->getOauthAccessToken();
            if (!$json) {
                unset($_SESSION['wx_redirect']);
                die('获取用户授权失败，请重新确认');
            }
            $_SESSION['open_id'] = $this->open_id = $json["openid"];
            $access_token = $json['access_token'];
            $_SESSION['user_token'] = $access_token;
            $_SESSION['token_time'] = time();
            $userinfo = $this->weObj->getUserInfo($this->open_id);
            if ($userinfo && !empty($userinfo['nickname'])) {
//                echo '1';
//                var_dump($userinfo);

                $this->wxuser = array(
                    'open_id' => $this->open_id,
                    'openid' => $this->open_id,
                    'nickname' => $userinfo['nickname'],
                    'sex' => intval($userinfo['sex']),
                    'province' => $userinfo['province'],
                    'city' => $userinfo['city'],
                    'headimgurl' => $userinfo['headimgurl'],
                    'subscribe' => $userinfo['subscribe']
                );
            } elseif (strstr($json['scope'], 'snsapi_userinfo') !== false) {
//                echo '2';
//
//                var_dump($userinfo);
                $userinfo = $this->weObj->getOauthUserinfo($access_token, $this->open_id);
                if ($userinfo && !empty($userinfo['nickname'])) {
                    $this->wxuser = array(
                        'open_id' => $this->open_id,
                        'openid' => $this->open_id,
                        'nickname' => $userinfo['nickname'],
                        'sex' => intval($userinfo['sex']),
                        'province' => $userinfo['province'],
                        'city' => $userinfo['city'],
                        'headimgurl' => $userinfo['headimgurl']
                    );
                } else {
                    return $this->open_id;
                }
            }
            if ($this->wxuser) {
                $_SESSION['wxuser'] = $this->wxuser;
                $_SESSION['open_id'] = $json["openid"];
                unset($_SESSION['wx_redirect']);
                return $this->open_id;
            }
            $scope = 'snsapi_userinfo';
        }
        if ($scope == 'snsapi_base') {
            $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $_SESSION['wx_redirect'] = $url;
        } else {
            $url = $_SESSION['wx_redirect'];
        }
        if (!$url) {
            unset($_SESSION['wx_redirect']);
            die('获取用户授权失败');
        }
        $oauth_url = $this->weObj->getOauthRedirect($url, "wxbase", $scope);
        header('Location: ' . $oauth_url);
    }

    public function wxoauthbase()
    {
        $scope = 'snsapi_base';
        $code = isset($_GET['code']) ? $_GET['code'] : '';
        $token_time = isset($_SESSION['token_time']) ? $_SESSION['token_time'] : 0;
        if (!$code && isset($_SESSION['open_id']) && isset($_SESSION['user_token']) && $token_time > time() - 3600) {
            $this->open_id = $_SESSION['open_id'];
            return $this->open_id;
        } else {
            $options = array(
                'token' => $this->token, //填写你设定的key
                'appid' => $this->appid, //填写高级调用功能的app id
                'appsecret' => $this->appsecret //填写高级调用功能的密钥
            );
//            $this->weObj = new TPWechat($options);
            if ($code) {
                $json = $this->weObj->getOauthAccessToken();
                if (!$json) {
                    unset($_SESSION['wx_redirect']);
                    die('获取用户授权失败，请重新确认');
                }
                $_SESSION['open_id'] = $this->open_id = $json["openid"];
                $access_token = $json['access_token'];
                $_SESSION['user_token'] = $access_token;
                $_SESSION['token_time'] = time();

                return;
            }
            if ($scope == 'snsapi_base') {
                $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                $_SESSION['wx_redirect'] = $url;
            } else {
                $url = $_SESSION['wx_redirect'];
            }
            if (!$url) {
                unset($_SESSION['wx_redirect']);
                die('获取用户授权失败');
            }
            $oauth_url = $this->weObj->getOauthRedirect($url, "wxbase", $scope);
            header('Location: ' . $oauth_url);
        }
    }

    public function logout(){
        session(null);
    }

    public function test1(){
        $this->open_id = session('open_id');
        $access_token = session('user_token');
        $userinfo = $this->weObj->getUserInfo($this->open_id);
        if ($userinfo && !empty($userinfo['nickname'])) {
            $wxuser = array(
                'open_id' => $this->open_id,
                'openid' => $this->open_id,
                'nickname' => $userinfo['nickname'],
                'sex' => intval($userinfo['sex']),
                'province' => $userinfo['province'],
                'city' => $userinfo['city'],
                'headimgurl' => $userinfo['headimgurl'],
                'subscribe' => $userinfo['subscribe']
            );
        }

        var_dump($userinfo);

        if(!$wxuser || $wxuser['subscribe'] == '0'){
            $data = array('code' => 201, 'msg' => '关注后才能投票');
            $this->ajaxReturn($data);
            return;
        }
    }


    public function getcookiiii(){
//        echo S('wechat_access_token' . 'wxb8ff917a0b440163');
        $user = $this->weObj->getUserInfo(I('param.json'));

//        'nickname' => $userinfo['nickname'],
//                'sex' => intval($userinfo['sex']),
//                'province' => $userinfo['province'],
//                'city' => $userinfo['city'],
//                'headimgurl' => $userinfo['headimgurl'],
//                'subscribe' => $userinfo['subscribe']
        echo '<p>'.$user['nickname'].'</p>'.'<img src="'.$user['headimgurl'].'">';
    }

    public function getname1(){
//        echo S('wechat_access_token' . 'wxb8ff917a0b440163');
//        'nickname' => $userinfo['nickname'],
//                'sex' => intval($userinfo['sex']),
//                'province' => $userinfo['province'],
//                'city' => $userinfo['city'],
//                'headimgurl' => $userinfo['headimgurl'],
//                'subscribe' => $userinfo['subscribe']
        $users = M('vote_log')->where('name like "%' .I('param.name').'%"')->order('createtime desc')->select();
//        var_dump($users);
        foreach($users as &$user){
            echo '<p>'.$user['name'].''.'<img src="'.$user['headurl'].'" style="width: 50px; height: 50px"> 时间:'.$user['createtime'].' 投票对象: '.$user['user_id'].'</p>';
        }
    }

    public function session(){
        var_dump($_SESSION);
    }
}